package com.strato.repository.monitor.v1_0_0.activator;

import java.io.File;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import com.strato.base.env.v1_0_0.GlobalEnvironment;
import com.strato.repository.monitor.v1_0_0.FileMonitor;
import com.strato.repository.monitor.v1_0_0.jpathwatch.JPathWatchDirectoryMonitor;
import com.strato.repository.monitor.v1_0_0.listener.RedeployListener;
import com.strato.repository.monitor.v1_0_0.recursive.RecursiveDirectoryMonitor;

public class Activator implements BundleActivator {

	static FileMonitor monitor=null;
	
	
	@Override
	public void start(BundleContext context) throws Exception {
		String rootDir=GlobalEnvironment.getInstance().get("strato.osgi.repository");
		if(rootDir==null){
			String catalinaHome=System.getProperty("catalina.home");
			File dir=new File(catalinaHome);
			File repDir=new File(dir,"/plugins");
			rootDir=repDir.getAbsolutePath();
			GlobalEnvironment.getInstance().set("strato.osgi.repository",rootDir);
		}
		String os=System.getProperty("os.name");
		int longInterval=30;
		int shortInterval=1;
		if(os==null){
			monitor=new RecursiveDirectoryMonitor(rootDir, longInterval);
		}else if(os.toUpperCase().indexOf("WINDOWS")==-1){
			monitor=new RecursiveDirectoryMonitor(rootDir, longInterval);
		}else{
			monitor=new JPathWatchDirectoryMonitor(rootDir, shortInterval);
		}
		monitor.addListener(new RedeployListener(context));
		monitor.start();
	}

	@Override
	public void stop(BundleContext bundleContext) throws Exception {
		if(monitor!=null){
			monitor.stop();
			monitor=null;
		}
	}

}
